//
//  OrderParticularsViewController.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/5/8.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "OrderParticularsViewController.h"

#import "OrderParticularsModel.h"

#import "OrderParticularsHeaderCell.h"
#import "OrderParticularsGoodsCell.h"
#import "OrderParticularsInfoCell.h"

#import "OrderEvaluationViewController.h"

#import "OrderApplyRefundView.h"

@interface OrderParticularsViewController ()<UITableViewDelegate,UITableViewDataSource>

///当前订单明细model
@property (nonatomic,strong) OrderParticularsModel *currentParticularsModel;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIView *bottomMenuView;//底部view 订单操作等

@property (nonatomic,assign) CGFloat orderHeaderHeight;
@property (nonatomic,assign) CGFloat orderGoodsHeight;
@property (nonatomic,assign) CGFloat orderInfoHeight;

@property (nonatomic,strong) UIButton *orderBtn1;
@property (nonatomic,strong) UIButton *orderBtn2;
@property (nonatomic,strong) UIButton *orderBtn3;

@end

@implementation OrderParticularsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topTitle = @"订单明细详情";
    self.topNavView.backgroundColor = MainBackColor;
    self.view.backgroundColor = MainBackColor;
    
    self.orderHeaderHeight = 200;
    self.orderGoodsHeight = 200;
    self.orderInfoHeight = 200;
    
    [self initUI];
    [self getData];
}
#pragma mark - data
-(void)getData{
    [NetWorkingOrder getProductOrderItemDetail:[NSString stringWithFormat:@"%ld",self.orderModel.ID] withSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        self.currentParticularsModel = [OrderParticularsModel paraWithDict:data];
        [self.tableView reloadData];
        [self reloadBottomMenuStatus];
    }];
    
}
-(void)reloadBottomMenuStatus{
    NSMutableArray *btnTitlesArr = [NSMutableArray array];
    if (self.currentParticularsModel.commentbtn == YES) {
        [btnTitlesArr addObject:@"去评价"];
    }
    if (self.currentParticularsModel.refundbtn == YES) {
        [btnTitlesArr addObject:@"申请退款"];
    }
    if (self.currentParticularsModel.rejectbtn == YES) {
        [btnTitlesArr addObject:@"申请退换货"];
    }
    if (self.currentParticularsModel.donebtn == YES) {
        [btnTitlesArr addObject:@"确认完成"];
    }
    if (self.currentParticularsModel.trackbtn == YES) {
        [btnTitlesArr addObject:@"查看物流"];
    }
    if (btnTitlesArr.count >= 1) {
        self.orderBtn1.hidden = NO;
        [self.orderBtn1 setTitle:btnTitlesArr[0] forState:normal];
    }else if (btnTitlesArr.count >= 2) {
        self.orderBtn1.hidden = NO;
        self.orderBtn2.hidden = NO;
        [self.orderBtn1 setTitle:btnTitlesArr[0] forState:normal];
        [self.orderBtn2 setTitle:btnTitlesArr[1] forState:normal];
    }else if (btnTitlesArr.count >= 3) {
        self.orderBtn1.hidden = NO;
        self.orderBtn2.hidden = NO;
        self.orderBtn3.hidden = NO;
        [self.orderBtn1 setTitle:btnTitlesArr[0] forState:normal];
        [self.orderBtn2 setTitle:btnTitlesArr[1] forState:normal];
        [self.orderBtn3 setTitle:btnTitlesArr[2] forState:normal];
    }
    if (btnTitlesArr.count <= 0) {
        self.bottomMenuView.hidden = YES;
        self.tableView.height = self.tableView.height + 55;
    }
}
#pragma mark - UI
-(void)initUI{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomMenuView];
    [self.bottomMenuView addSubview:self.orderBtn1];
    [self.bottomMenuView addSubview:self.orderBtn2];
    [self.bottomMenuView addSubview:self.orderBtn3];
}
#pragma mark - lazy
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kHeight_NavBar, ScreenWidth, ScreenHeight-kSafe_Bottom-55 - kHeight_NavBar) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.clearColor;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 0.1f)];
        [_tableView setTableHeaderView:view];
    }
    return _tableView;
}
- (UIView *)bottomMenuView{
    if (!_bottomMenuView) {
        _bottomMenuView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 52 - kSafe_Bottom, ScreenWidth, 52+kSafe_Bottom)];
        _bottomMenuView.backgroundColor = UIColor.whiteColor;
        
        UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        lineV.backgroundColor = MainPureColor(233);
        [_bottomMenuView addSubview:lineV];
    }
    return _bottomMenuView;
}
- (UIButton *)orderBtn1{
    if (!_orderBtn1) {
        _orderBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        _orderBtn1.frame = CGRectMake(ScreenWidth - 100, 10, 84, 30);
        _orderBtn1.clipsToBounds = YES;
        _orderBtn1.layer.cornerRadius = 15;
        _orderBtn1.backgroundColor = RGB(255, 34, 21);
        [_orderBtn1.titleLabel setFont:FontSet(14)];
        [_orderBtn1 setTitleColor:UIColor.whiteColor forState:normal];
        [_orderBtn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _orderBtn1.hidden = YES;
    }
    return _orderBtn1;
}
- (UIButton *)orderBtn2{
    if (!_orderBtn2) {
        _orderBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
        _orderBtn2.frame = CGRectMake(self.orderBtn1.left - 100, self.orderBtn1.top, 84, 30);
        _orderBtn2.clipsToBounds = YES;
        _orderBtn2.layer.cornerRadius = 15;
        [_orderBtn2 setTitleColor:MainPureColor(119) forState:normal];
        _orderBtn2.layer.borderWidth = 1;
        _orderBtn2.layer.borderColor = MainPureColor(220).CGColor;
        [_orderBtn2.titleLabel setFont:FontSet(14)];
        [_orderBtn2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _orderBtn2.hidden = YES;
    }
    return _orderBtn2;
}
- (UIButton *)orderBtn3{
    if (!_orderBtn3) {
        _orderBtn3 = [UIButton buttonWithType:UIButtonTypeCustom];
        _orderBtn3.frame = CGRectMake(self.orderBtn2.left - 100, self.orderBtn1.top, 84, 30);
        _orderBtn3.clipsToBounds = YES;
        _orderBtn3.layer.cornerRadius = 15;
        [_orderBtn3 setTitleColor:MainPureColor(119) forState:normal];
        _orderBtn3.layer.borderWidth = 1;
        _orderBtn3.layer.borderColor = MainPureColor(220).CGColor;
        [_orderBtn3.titleLabel setFont:FontSet(14)];
        [_orderBtn3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _orderBtn3.hidden = YES;
    }
    return _orderBtn3;
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return self.orderHeaderHeight;
    }else if (indexPath.row == 1) {
        return self.orderGoodsHeight;
    }else{
        return self.orderInfoHeight;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF(self);
    if (indexPath.row == 0) {
        static NSString *cellId = @"OrderParticularsHeaderCell";
        OrderParticularsHeaderCell *headerCell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!headerCell) {
            headerCell = [[OrderParticularsHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        headerCell.model = self.currentParticularsModel;
        [headerCell setUpdateCellHeightBlock:^(CGFloat height) {
            self.orderHeaderHeight = height;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }];
        return headerCell;
    }else if (indexPath.row == 1) {
        static NSString *cellId = @"OrderParticularsGoodsCell";
        OrderParticularsGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!goodsCell) {
            goodsCell = [[OrderParticularsGoodsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        goodsCell.model = self.currentParticularsModel;
        [goodsCell setUpdateCellHeightBlock:^(CGFloat height) {
            self.orderGoodsHeight = height;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }];
        return goodsCell;
    }else{
        static NSString *cellId = @"OrderParticularsInfoCell";
        OrderParticularsInfoCell *infoCell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!infoCell) {
            infoCell = [[OrderParticularsInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        [infoCell setUpdateCellHeightBlock:^(CGFloat height) {
            self.orderInfoHeight = height;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }];
        infoCell.model = self.currentParticularsModel;
        return infoCell;
    }
}
#pragma mark - SEL
//底部按钮点击事件
-(void)btnClick:(UIButton *)btn{
    if ([btn.titleLabel.text isEqualToString:@"申请退换货"]){
        [self applyRefundWithType:0];
    }else if ([btn.titleLabel.text isEqualToString:@"查看物流"]){
        [self checkTheLogistics];
    }else if ([btn.titleLabel.text isEqualToString:@"申请退款"]){
        [self applyRefundWithType:1];
    }else if ([btn.titleLabel.text isEqualToString:@"确认完成"]){
        [self confirmOrderCompleted];
    }else if ([btn.titleLabel.text isEqualToString:@"去评价"]){
        [self toEvaluateClick];
    }
}
//申请退换货
-(void)applyRefundWithType:(NSInteger)type{
    WEAKSELF(self);
    OrderApplyRefundView *refundView = [[OrderApplyRefundView alloc] initWithTitle:(type == 0?@"申请退换货":@"申请退款")];
    [refundView show];
    NSString *itemID = [NSString stringWithFormat:@"%ld",(long)self.currentParticularsModel.ID];
    [refundView setRefundBlock:^(NSString * _Nonnull refundReason) {
        if (type == 0) {
            [NetWorkingOrder applyOrderReject:itemID note:refundReason withSuccessBlock:^(id  _Nonnull responseObj) {
                [[XNProgressHUD shared] showSuccessWithTitle:@"已为您申请退换货!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self popAndPostRefreshNotificationWithListType:4];
                });
            }];
        }else{
            [NetWorkingOrder applyOrderRefund:itemID note:refundReason withSuccessBlock:^(id  _Nonnull responseObj) {
                [[XNProgressHUD shared] showSuccessWithTitle:@"已为您申请退款!"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self popAndPostRefreshNotificationWithListType:5];
                });
            }];
        }
    }];
}
//查看物流
-(void)checkTheLogistics{
}
//确认完成
-(void)confirmOrderCompleted{
    NSString *itemID = [NSString stringWithFormat:@"%ld",(long)self.currentParticularsModel.ID];
    [OrderManager confrimDoneWithID:itemID withSuccessBlock:^{
        [self getData];
        [self popAndPostRefreshNotificationWithListType:4];
    }];
}
//去评价
-(void)toEvaluateClick{
    OrderEvaluationViewController *vc = [[OrderEvaluationViewController alloc] init];
    vc.itemID = [NSString stringWithFormat:@"%ld",(long)self.currentParticularsModel.ID];
    vc.goodsName = self.currentParticularsModel.name;
    vc.goodsLogo = self.currentParticularsModel.picture;
    [self.navigationController pushViewController:vc animated:YES];
}


//发送通知让订单列表刷新 并返回上级界面
-(void)popAndPostRefreshNotificationWithListType:(NSInteger)listType{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
        NSDictionary *dic = @{@"listType":@(listType)};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshOrderListNotification" object:nil userInfo:dic];
    });
}


@end
